package com.wheesper.www.WheesperServer.Net.Base;

import java.net.InetSocketAddress;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;

import com.wheesper.www.WheesperServer.Common.Request;
import com.wheesper.www.WheesperServer.Common.TaskQueue;
import com.wheesper.www.WheesperServer.Net.Session.SessionManager;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;


public class WheesperServer {
	private final int port;
	private TaskQueue<Request> _taskqueue;
	
	public WheesperServer(int port,TaskQueue<Request> _taskqueue) {
		this.port = port;
		this._taskqueue = _taskqueue;
	}
	
	public void start() throws Exception{
		EventLoopGroup group = new NioEventLoopGroup();
		System.out.println("Wheesper Server starting....");
		try {
			ServerBootstrap boots = new ServerBootstrap();
			boots.group(group)
			.channel(NioServerSocketChannel.class)
			.localAddress(new InetSocketAddress(port))
			.childHandler(new ChannelInitializer<SocketChannel>(){

				@Override
				protected void initChannel(SocketChannel ch) throws Exception {
					ch.pipeline().addLast(new SessionChannelHandler(_taskqueue,SessionManager.Instance()));
				}
				
			});
			System.out.println("Wheesper Server Listen at port " + port);
			ChannelFuture f = boots.bind().sync();
			f.channel().closeFuture().sync();
		}finally {
			group.shutdownGracefully().sync();
		}
	}
}
